package com.egao.common.module.system.transfer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentInfo;
import com.egao.common.module.student.service.StudentInfoService;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;

/**
 * 学生数据迁移
 *
 * @author lym
 */
@Api(tags = "学生相关数据迁移")
@RestController
@Slf4j
public class StudentDataController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private UserService userService;

    @Value("${old.datasource.jyurl}")
    private String jyurl;
    @Value("${old.datasource.syurl}")
    private String syurl;
    @Value("${old.datasource.username}")
    private String userName;
    @Value("${old.datasource.password}")
    private String password;

    @Value("${minio.endpoint}")
    private String minioUrl;

    @ApiOperation("生源数据迁移")
    public JsonResult student() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        Connection conn1 = null;
        Statement st1 = null;
        ResultSet rs1 = null;

        String xhError = "";

        TimeInterval timeInterval = DateUtil.timer();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(syurl, userName, password);
            st = conn.createStatement();
            String sql = "SELECT o.`code`, s.*, si.* FROM student s LEFT JOIN student_info si ON si.student_id = s.id LEFT JOIN sys_office o ON o.id = s.office_id WHERE s.id = si.student_id AND s.del_flag = '0'";
            st = conn.createStatement();
            rs = st.executeQuery(sql);

            conn1 = DriverManager.getConnection(jyurl, userName, password);
            st1 = conn1.createStatement();

            while (rs.next()) {
                Student student = new Student();

                student.setOldId(rs.getString("id"));

                student.setUserId(0);
                student.setYearId(rs.getInt("year"));
                student.setXh(rs.getString("xh"));
                student.setMobile(rs.getString("mobile"));
                student.setEmail(rs.getString("email"));
                student.setCollegeCode(rs.getString("code"));
                student.setMajorCode(rs.getString("major_id"));

                student.setBjhm(rs.getString("bjhm"));
                student.setXm(rs.getString("xm"));
                student.setXb(rs.getString("xb"));
                student.setXl(rs.getString("xl"));
                student.setXz(rs.getInt("xz"));
                student.setXw(rs.getString("xw"));
                student.setXwlb(rs.getString("xwlb"));
                student.setGrade(rs.getString("grade"));
                student.setPyfs(rs.getString("pyfs"));
                student.setCsrq(DateUtil.parse(rs.getString("csrq")));
                student.setRxsj(DateUtil.parse(rs.getString("rxsj")));
                student.setBysj(DateUtil.parse(rs.getString("bysj")));
                student.setSysf(rs.getString("sysf"));
                student.setSyszd(rs.getString("syszd"));
                student.setSfzhm(rs.getString("sfzhm"));
                student.setKsh(rs.getString("ksh"));
                student.setZzmm(rs.getString("zzmm"));
                student.setMz(rs.getString("mz"));
                student.setKnslb(rs.getString("knslb"));
                student.setJzbfdxbz(rs.getString("jzbfdxbz"));
                student.setHksfzrxx(rs.getString("hksfzrxx"));
                student.setXjzt(rs.getString("xjzt"));
                student.setCxsydm(rs.getString("cxsydm"));
                student.setXxfs(rs.getString("xxfs"));

                student.setQuestionnaireState(rs.getString("questionnaire_flag"));
                student.setStudentState(rs.getString("student_flag"));

                String officeFlag = rs.getString("office_flag");
                if ("1".equals(officeFlag)) {
                    officeFlag = "2";
                }
                if ("2".equals(officeFlag)) {
                    officeFlag = "1";
                }
                student.setCollegeState(officeFlag);

                String schoolFlag = rs.getString("school_flag");
                if ("1".equals(schoolFlag)) {
                    schoolFlag = "2";
                }
                if ("2".equals(schoolFlag)) {
                    schoolFlag = "1";
                }
                student.setSchoolState(schoolFlag);

                String delayFlag = rs.getString("delay_flag");
                if ("0".equals(delayFlag)) {
                    delayFlag = "1";
                } else {
                    delayFlag = "0";
                }
                student.setDelayState(delayFlag);

                // inten 由就业学生信息来更新

                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setStudentId(student.getId());
                studentInfo.setUserId(student.getUserId());
                studentInfo.setXh(student.getXh());
                studentInfo.setZxwyyz(rs.getString("zxwyyz"));
                studentInfo.setZxjh(rs.getString("zxjh"));
                studentInfo.setYjfx(rs.getString("yjfx"));
                studentInfo.setFxxw(rs.getString("fxxw"));
                studentInfo.setFxzy(rs.getString("fxzy"));
                studentInfo.setHyzk(rs.getString("hyzk"));
                studentInfo.setDxhwpdw(rs.getString("dxhwpdw"));
                studentInfo.setDxDwzzjgdm(rs.getString("dx_dwzzjgdm"));
                studentInfo.setDxDwxz(rs.getString("dx_dwxz"));
                studentInfo.setDxDwhy(rs.getString("dx_dwhy"));
                studentInfo.setDxDwszd(rs.getString("dx_dwszd"));
                studentInfo.setDxDwlxr(rs.getString("dx_dwlxr"));
                studentInfo.setDxDwlxdh(rs.getString("dx_dwlxdh"));
                studentInfo.setJtdz(rs.getString("jtdz"));
                studentInfo.setJtyzbm(rs.getString("jtyzbm"));
                studentInfo.setJjlxr(rs.getString("jjlxr"));
                studentInfo.setJjlxrdh(rs.getString("jjlxrdh"));
                studentInfo.setBzkxl(rs.getString("bzkxl"));
                studentInfo.setBzkcc(rs.getString("bzkcc"));
                studentInfo.setBzkyxmc(rs.getString("bzkyxmc"));
                studentInfo.setXyyj(rs.getString("xyyj"));
                studentInfo.setXylxr(rs.getString("xylxr"));
                studentInfo.setXylxdh(rs.getString("xylxdh"));
                studentInfo.setXxyj(rs.getString("xxyj"));
                studentInfo.setXxlxr(rs.getString("xxlxr"));
                studentInfo.setXxlxdh(rs.getString("xxlxdh"));

                studentInfo.setAhtc(rs.getString("ahtc"));
                studentInfo.setGrjn(rs.getString("grjn"));
                studentInfo.setShsjjljrzqk(rs.getString("shsjjljrzqk"));
                studentInfo.setHjjfbzpqk(rs.getString("hjjfbzpqk"));
                studentInfo.setZykyhdhxshd(rs.getString("zykyhdhxshd"));
                studentInfo.setDstjyj(rs.getString("dstjyj"));
                studentInfo.setGrzjhqzyj(rs.getString("grzjhqzyj"));
                studentInfo.setBz(rs.getString("bz"));

                studentInfo.setYxdq(rs.getString("yxdq"));
                studentInfo.setYxdwxz(rs.getString("yxdwxz"));
                studentInfo.setYxdwhy(rs.getString("yxdwhy"));
                studentInfo.setYxzwlb(rs.getString("yxzwlb"));
                studentInfo.setYxyx(rs.getString("yxyx"));
                studentInfo.setQq(rs.getString("zxwyyz"));

                String pwd = IdUtil.simpleUUID();

                // 保存
                User user = new User();
                user.setUsername(student.getXh());
                user.setName(student.getXm());
                user.setCollegeCode(student.getCollegeCode());
                user.setPassword(userService.encodePsw(pwd));
                user.setState(0);
                user = userService.saveUserStudent(user);
                if (user == null || user.getUserId() == null) {
                    continue;
                }

                student.setUserId(user.getUserId());

                String sql1 = "SELECT inten_name, inten_address, inten_salary, inten_nature, inten_industry, inten_scale, resume FROM student WHERE loginname = '" + student.getXh() + "' ORDER BY create_date DESC LIMIT 1";
                st1 = conn1.createStatement();
                rs1 = st1.executeQuery(sql1);

                while (rs1.next()) {
                    student.setIntenName(rs1.getString("inten_name"));
                    student.setIntenAddress(rs1.getString("inten_address"));
                    student.setIntenSalary(rs1.getString("inten_salary"));
                    student.setIntenNature(rs1.getString("inten_nature"));
                    student.setIntenIndustry(rs1.getString("inten_industry"));
                    student.setIntenScale(rs1.getString("inten_scale"));
                    String resume = rs1.getString("resume");
                    String resumeName = "";
                    if (!StrUtil.isBlank(resume)) {
                        resume = minioUrl + resume;
                        if (resume.contains("/")) {
                            resumeName = resume.substring(resume.lastIndexOf("/") + 1);
                        }
                    }
                    student.setResumeUrl(resume);
                    student.setResumeName(resumeName);
                }

                studentService.save(student);
                if (student == null || student.getId() == null) {
                    xhError += student.getXh() + ",";
                    continue;
                }

                studentInfo.setUserId(user.getUserId());
                studentInfo.setStudentId(student.getId());
                studentInfoService.save(studentInfo);
            }

            return JsonResult.ok(timeInterval.intervalMinute() + "--" +xhError);
        } catch (ClassNotFoundException | SQLException e) {
            log.error("Student Data：" + timeInterval.intervalMinute() + "分。" + e.getMessage());
            e.printStackTrace();
        }
        return JsonResult.ok(xhError);
    }

}
